import axios, {AxiosResponse, InternalAxiosRequestConfig} from 'axios';

// Define types for function parameters
interface GetAxiosParams {
    url: string;
    params?: Record<string, unknown>;
}

interface PostAxiosParams {
    url: string;
    data: Record<string, unknown>;
}

export const LOGIN_KEY = 'info_3'
export const COOKIE_KEY = 'xx_3'
export const LAST_PLAYBACK_TIME = 'last_PlaybackTime_'

// Environment-specific baseURL
export let baseURL: string;
if (process.env.NODE_ENV === 'production') {
    baseURL = 'https://www.tjbaowj.top'; // Production URL
} else {
    baseURL = 'http://www.tjbaowj.top'; // Development URL
    // baseURL = 'http://heath-capi.xunxinsoft.com'; // Development URL
}

// Response interceptor
axios.interceptors.response.use(
    (response: AxiosResponse): AxiosResponse => {
        return response;
    },
    (error): Promise<never> => {
        return Promise.reject(error);
    }
);

// Request interceptor
axios.interceptors.request.use(
    (config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
        console.log(config);
        if (config.headers) {
            const userInfo = localStorage.getItem(LOGIN_KEY)
            if (userInfo) {
                const info = JSON.parse(userInfo)
                // config.headers['Authorization'] = 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI0MDM3ZDExMy0wNDdjLTQ1NzEtYjYwOS1iZDM5MjNhYzY2NWMiLCJjcmVhdGVkIjoxNzEyOTIyMjAyMzAwLCJleHAiOjE3MTM1MjcwMDJ9.VbZL5ZkySx6TSa9GPAOhz0q5d_V5cth0nCr69dfs6TKIr3psZFX8bqzMUORgJwKZWV4eq2QJb2-eIXK5Ve7hAQ'
                config.headers['Authorization'] = info.tokenHead + ' ' + info.token
            }
        }
        config.baseURL = baseURL;
        config.timeout = 10000;
        return config;
    },
    (error): Promise<never> => {
        return Promise.reject(error);
    }
);

// GET request function
export function getAxios({url, params = {}}: GetAxiosParams): Promise<any> {
    console.log('getAxios', url, params)
    return new Promise((resolve, reject) => {
        axios
            .get(url, {
                params,
            })
            .then((res) => {
                resolve(res.data);
            })
            .catch((err) => {
                console.log(err, '1');
                reject(err);
            });
    });
}

// POST request function
export function postAxios({url, data}: PostAxiosParams): Promise<any> {
    console.log('postAxios', url, data)
    return new Promise((resolve, reject) => {
        axios({url, method: 'post', data,})
            .then((res) => {
                resolve(res.data);
            })
            .catch((err) => {
                reject(err);
            });
    });
}

export default axios;

export function getDomain() {
    const protocol = window.location.protocol; // 获取协议，例如 'http:'
    const hostname = window.location.hostname; // 获取主机名，例如 'www.example.com'
    const port = window.location.port ? `:${window.location.port}` : ''; // 获取端口号，如果有的话
    return `${protocol}//${hostname}${port}`
}
